import { NextResponse } from "next/server";
import { getUser } from "@/lib/authUtils";
const COS = require('cos-nodejs-sdk-v5');

const cos = new COS({
  SecretId: process.env.TENCENT_SECRET_ID,
  SecretKey: process.env.TENCENT_SECRET_KEY,
});

export async function POST(request: Request): Promise<NextResponse> {
  const userid = await getUser(request);
  if (!userid) {
    return NextResponse.json(
      { error: '未授权或登录信息过期，请登录' },
      { status: 401 }
    );
  }
  if (userid instanceof NextResponse) {
    return userid;
  }
  try {
    const formData = await request.formData();
    const file = formData.get('file') as File;
    
    if (!file) {
      return NextResponse.json(
        { error: "No file provided" },
        { status: 400 }
      );
    }

    const buffer = Buffer.from(await file.arrayBuffer());
    const timestamp = Date.now();
    const uniqueKey = `subtitles/${timestamp}_${file.name}`;

    // 上传文件到COS
    const cosResult = await new Promise<any>((resolve, reject) => {
      cos.putObject({
        Bucket: process.env.TENCENT_COS_BUCKET,
        Region: process.env.TENCENT_COS_REGION,
        Key: uniqueKey,
        Body: buffer,
        ContentType: file.type,
      }, function(err: Error, data: any) {
        if (err) reject(err);
        else resolve(data);
      });
    });

    // 生成5小时有效的URL
    const fileUrl = await new Promise<string>((resolve, reject) => {
      cos.getObjectUrl({
        Bucket: process.env.TENCENT_COS_BUCKET,
        Region: process.env.TENCENT_COS_REGION,
        Key: uniqueKey,
        Method: 'GET',
        Expires: 18000, // 5小时有效期
      }, function(err: Error, data: any) {
        if (err) reject(err);
        else resolve(data.Url);
      });
    });

    return NextResponse.json({
      url: fileUrl,
      key: uniqueKey,
      ...cosResult
    });

  } catch (error) {
    console.error("Error uploading file:", error);
    return NextResponse.json(
      { error: "Failed to upload file" },
      { status: 500 }
    );
  }
}
